package net.maku.framework.mybatis.handler;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class RemainingTimeHandler extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 启动定时器，定期推送剩余时间
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    long remainingTime = calculateRemainingTime(); // 计算剩余时间
                    session.sendMessage(new TextMessage(String.valueOf(remainingTime)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000); // 每隔 1 秒推送一次
    }

    private long calculateRemainingTime() {
        // 模拟剩余时间计算
        long endTime = 1735660799000L; // 2024-12-31T23:59:59
        long now = System.currentTimeMillis();
        return Math.max(0, endTime - now); // 返回剩余时间（毫秒）
    }
}
